// 棋子移动规则计算器
export default class MoveCalculator {
  constructor(boardMatrix) {
    this.boardMatrix = boardMatrix
  }

  // 计算所有可能的移动
  calculatePossibleMoves(row, col, piece, enPassantTarget, castlingState) {
    const moves = []
    
    switch (piece.type) {
      case 'pawn':
        this.calculatePawnMoves(row, col, piece.color, moves, enPassantTarget)
        break
      case 'rook':
        this.calculateRookMoves(row, col, piece.color, moves)
        break
      case 'knight':
        this.calculateKnightMoves(row, col, piece.color, moves)
        break
      case 'bishop':
        this.calculateBishopMoves(row, col, piece.color, moves)
        break
      case 'queen':
        this.calculateQueenMoves(row, col, piece.color, moves)
        break
      case 'king':
        this.calculateKingMoves(row, col, piece.color, moves, castlingState)
        break
    }
    
    // 过滤掉会导致己方王被将军的移动
    return moves.filter(move => !this.willMoveExposeKing(row, col, move.row, move.col, piece))
  }

  // 计算兵的移动
  calculatePawnMoves(row, col, color, moves, enPassantTarget) {
    console.log(`计算兵的移动 - 当前位置: [${row},${col}], 颜色: ${color}`)
    const direction = color === 'white' ? -1 : 1
    const startRow = color === 'white' ? 6 : 1
    
    // 普通前进 - 检查前方格子是否为空（不能移动到有任何棋子的格子）
    if (this.isValidPosition(row + direction, col) && 
        !this.boardMatrix[row + direction][col]) {
      const singleMove = { row: row + direction, col }
      console.log(`可以前进一格到: [${singleMove.row},${singleMove.col}]`)
      moves.push(singleMove)
      
      // 初始位置可前进两格 - 只有在兵位于其真正的初始位置时才允许
      if (row === startRow && 
          this.isValidPosition(row + 2 * direction, col) &&
          !this.boardMatrix[row + direction][col] && // 检查路径上的第一个格子
          !this.boardMatrix[row + 2 * direction][col]) { // 检查目标格子
        const doubleMove = { 
          row: row + 2 * direction, 
          col,
          isDoublePawnMove: true
        }
        console.log(`初始位置可以前进两格到: [${doubleMove.row},${doubleMove.col}]`)
        moves.push(doubleMove)
      }
    }

    // 斜向吃子
    [-1, 1].forEach(colOffset => {
      const targetRow = row + direction
      const targetCol = col + colOffset
      
      if (this.isValidPosition(targetRow, targetCol)) {
        const targetPiece = this.boardMatrix[targetRow][targetCol]
        
        // 新规则：只有当斜前方格子有棋子时才能斜向移动并吃掉敌方棋子
        if (targetPiece) {
          if (targetPiece.color !== color) {
            const captureMove = { 
              row: targetRow, 
              col: targetCol,
              isCapture: true,
              capturedPiece: targetPiece // 记录被吃掉的棋子信息
            }
            console.log(`可以斜向吃子到: [${targetRow},${targetCol}], 被吃掉的棋子类型: ${targetPiece.type}`)
            moves.push(captureMove)
          }
        }
        // 保持吃过路兵的特殊规则
        else if (enPassantTarget && 
            targetRow === enPassantTarget.row && 
            targetCol === enPassantTarget.col) {
          // 吃过路兵
          const enPassantMove = {
            row: targetRow,
            col: targetCol,
            isEnPassant: true,
            captureRow: row,
            captureCol: targetCol
          }
          console.log(`可以吃过路兵到: [${targetRow},${targetCol}]`)
          moves.push(enPassantMove)
        }
      }
    })
  }

  // 计算车的移动
  calculateRookMoves(row, col, color, moves) {
    // 向上
    this.calculateLineMove(row, col, -1, 0, color, moves)
    // 向下
    this.calculateLineMove(row, col, 1, 0, color, moves)
    // 向左
    this.calculateLineMove(row, col, 0, -1, color, moves)
    // 向右
    this.calculateLineMove(row, col, 0, 1, color, moves)
  }

  // 计算马的移动
  calculateKnightMoves(row, col, color, moves) {
    const knightMoves = [
      [-2, -1], [-2, 1], [-1, -2], [-1, 2],
      [1, -2], [1, 2], [2, -1], [2, 1]
    ]

    for (const [dRow, dCol] of knightMoves) {
      const newRow = row + dRow
      const newCol = col + dCol
      
      if (this.isValidPosition(newRow, newCol)) {
        const target = this.boardMatrix[newRow][newCol]
        if (!target || target.color !== color) {
          moves.push({ row: newRow, col: newCol })
        }
      }
    }
  }

  // 计算象的移动
  calculateBishopMoves(row, col, color, moves) {
    // 左上
    this.calculateLineMove(row, col, -1, -1, color, moves)
    // 右上
    this.calculateLineMove(row, col, -1, 1, color, moves)
    // 左下
    this.calculateLineMove(row, col, 1, -1, color, moves)
    // 右下
    this.calculateLineMove(row, col, 1, 1, color, moves)
  }

  // 计算后的移动（车+象的组合）
  calculateQueenMoves(row, col, color, moves) {
    this.calculateRookMoves(row, col, color, moves)
    this.calculateBishopMoves(row, col, color, moves)
  }

  // 计算王的移动
  calculateKingMoves(row, col, color, moves, castlingState) {
    const directions = [
      { dr: -1, dc: -1 }, { dr: -1, dc: 0 }, { dr: -1, dc: 1 },
      { dr: 0, dc: -1 },  { dr: 0, dc: 1 },
      { dr: 1, dc: -1 },  { dr: 1, dc: 0 }, { dr: 1, dc: 1 }
    ]

    directions.forEach(({ dr, dc }) => {
      const newRow = row + dr
      const newCol = col + dc
      
      if (this.isValidPosition(newRow, newCol)) {
        const targetPiece = this.boardMatrix[newRow][newCol]
        if (!targetPiece || targetPiece.color !== color) {
          moves.push({ row: newRow, col: newCol })
        }
      }
    })

    // 王车易位
    if (castlingState) {
      const backRow = color === 'white' ? 7 : 0
      const kingNotMoved = color === 'white' ? !castlingState.whiteKingMoved : !castlingState.blackKingMoved
      
      if (row === backRow && col === 4 && kingNotMoved) {
        // 短易位（王翼）
        const rightRookNotMoved = color === 'white' ? !castlingState.whiteRightRookMoved : !castlingState.blackRightRookMoved
        if (rightRookNotMoved && 
            !this.boardMatrix[backRow][5] && 
            !this.boardMatrix[backRow][6] && 
            this.boardMatrix[backRow][7]?.type === 'rook') {
          moves.push({
            row: backRow,
            col: 6,
            isCastling: true,
            rookFromCol: 7,
            rookToCol: 5
          })
        }
        
        // 长易位（后翼）
        const leftRookNotMoved = color === 'white' ? !castlingState.whiteLeftRookMoved : !castlingState.blackLeftRookMoved
        if (leftRookNotMoved && 
            !this.boardMatrix[backRow][3] && 
            !this.boardMatrix[backRow][2] && 
            !this.boardMatrix[backRow][1] && 
            this.boardMatrix[backRow][0]?.type === 'rook') {
          moves.push({
            row: backRow,
            col: 2,
            isCastling: true,
            rookFromCol: 0,
            rookToCol: 3
          })
        }
      }
    }
  }

  // 计算直线移动（用于车、象、后）
  calculateLineMove(row, col, rowDir, colDir, color, moves) {
    let newRow = row + rowDir
    let newCol = col + colDir

    while (this.isValidPosition(newRow, newCol)) {
      const target = this.boardMatrix[newRow][newCol]
      
      if (!target) {
        moves.push({ row: newRow, col: newCol })
      } else {
        if (target.color !== color) {
          moves.push({ row: newRow, col: newCol })
        }
        break
      }
      
      newRow += rowDir
      newCol += colDir
    }
  }

  // 检查位置是否有效
  isValidPosition(row, col) {
    return row >= 0 && row < 8 && col >= 0 && col < 8
  }

  // 更新棋盘矩阵
  updateBoardMatrix(newMatrix) {
    this.boardMatrix = newMatrix
  }

  // 检查移动是否会导致己方王被将军
  willMoveExposeKing(fromRow, fromCol, toRow, toCol, piece) {
    // 创建棋盘矩阵的副本
    const tempMatrix = this.boardMatrix.map(row => [...row])
    
    // 模拟移动
    const capturedPiece = tempMatrix[toRow][toCol]
    tempMatrix[toRow][toCol] = piece
    tempMatrix[fromRow][fromCol] = null
    
    // 找到己方王的位置
    let kingRow, kingCol
    for (let r = 0; r < 8; r++) {
      for (let c = 0; c < 8; c++) {
        const p = tempMatrix[r][c]
        if (p && p.type === 'king' && p.color === piece.color) {
          kingRow = r
          kingCol = c
          break
        }
      }
    }
    
    // 检查移动后是否会被将军
    return this.isKingInCheck(kingRow, kingCol, piece.color, tempMatrix)
  }

  // 检查指定位置的王是否被将军
  isKingInCheck(kingRow, kingCol, kingColor, matrix) {
    // 检查对方的车、后的攻击
    const rookDirections = [{dr: -1, dc: 0}, {dr: 1, dc: 0}, {dr: 0, dc: -1}, {dr: 0, dc: 1}]
    for (const {dr, dc} of rookDirections) {
      let r = kingRow + dr
      let c = kingCol + dc
      while (this.isValidPosition(r, c)) {
        const piece = matrix[r][c]
        if (piece) {
          if (piece.color !== kingColor && (piece.type === 'rook' || piece.type === 'queen')) {
            return true
          }
          break
        }
        r += dr
        c += dc
      }
    }
    
    // 检查对方的象、后的攻击
    const bishopDirections = [{dr: -1, dc: -1}, {dr: -1, dc: 1}, {dr: 1, dc: -1}, {dr: 1, dc: 1}]
    for (const {dr, dc} of bishopDirections) {
      let r = kingRow + dr
      let c = kingCol + dc
      while (this.isValidPosition(r, c)) {
        const piece = matrix[r][c]
        if (piece) {
          if (piece.color !== kingColor && (piece.type === 'bishop' || piece.type === 'queen')) {
            return true
          }
          break
        }
        r += dr
        c += dc
      }
    }
    
    // 检查对方的马的攻击
    const knightMoves = [
      [-2, -1], [-2, 1], [-1, -2], [-1, 2],
      [1, -2], [1, 2], [2, -1], [2, 1]
    ]
    for (const [dr, dc] of knightMoves) {
      const r = kingRow + dr
      const c = kingCol + dc
      if (this.isValidPosition(r, c)) {
        const piece = matrix[r][c]
        if (piece && piece.color !== kingColor && piece.type === 'knight') {
          return true
        }
      }
    }
    
    // 检查对方的兵的攻击
    const pawnDirection = kingColor === 'white' ? -1 : 1
    const pawnAttacks = [{dr: pawnDirection, dc: -1}, {dr: pawnDirection, dc: 1}]
    for (const {dr, dc} of pawnAttacks) {
      const r = kingRow + dr
      const c = kingCol + dc
      if (this.isValidPosition(r, c)) {
        const piece = matrix[r][c]
        if (piece && piece.color !== kingColor && piece.type === 'pawn') {
          return true
        }
      }
    }
    
    // 检查对方的王的攻击（防止两个王相邻）
    const kingMoves = [
      {dr: -1, dc: -1}, {dr: -1, dc: 0}, {dr: -1, dc: 1},
      {dr: 0, dc: -1}, {dr: 0, dc: 1},
      {dr: 1, dc: -1}, {dr: 1, dc: 0}, {dr: 1, dc: 1}
    ]
    for (const {dr, dc} of kingMoves) {
      const r = kingRow + dr
      const c = kingCol + dc
      if (this.isValidPosition(r, c)) {
        const piece = matrix[r][c]
        if (piece && piece.color !== kingColor && piece.type === 'king') {
          return true
        }
      }
    }
    
    return false
  }
}